const inquirer = require("inquirer");
const { fetchRepoList,fetchTagList } = require("./request");
const { wrapLoading } = require("./util");
const downloadGitRepo = require('download-git-repo');
const util = require('util');
const path = require('path');


class Creator {
    constructor (projectName,target){
        this.name = projectName;
        this.target = target;
        this.downloadGitRepo = util.promisify(downloadGitRepo);
    }
    // 获取模板项目
    async fetchRepo(){
        // 新增loading 以及 失败重新获取
        let repos = await wrapLoading(fetchRepoList,'waiting fetch template');
        // let repos = await fetchRepoList();
        // // console.log(repos,'仓库列表');
        if(!repos) return;
        repos = repos.map(item => item.name);
        let { repo } = await inquirer.prompt({
            name: 'repo',
            type: 'list',
            choices: repos,
            message: 'please choose a template to create a project'
        })
        // // console.log(repo);
        return repo;
    }
    // 获取项目对应版本号
    async fetchTag(repo){
        let tags = await wrapLoading(fetchTagList,'waiting fetch tag', repo);
        console.log(tags);
        if(!tags) return;
        tags = tags.map(item => item.name);
        let { tag } = await inquirer.prompt({
            name: 'tag',
            type: 'list',
            choices: tags,
            message: 'please choose a tag to create a project'
        })
        return tag
    }
    // 根据仓库和tag下载指定模板
    async download(repo,tag){
        // 1. 拼接处下载路径
        let requestUrl = `zhu-cli/${repo}${tag ? '#' + tag : ''}`;
        // 2. 将资源下载到指定的位置 (后续可以增加缓存功能 w-todo)
        await wrapLoading(this.downloadGitRepo,'waiting down repo', requestUrl,path.resolve(process.cwd(),`${repo}@${tag}`));

        return this.target;
    }

    async create(){
        // 1. 先拉取当前组织下的模板
        let repo = await this.fetchRepo();
        // 2. 在通过模板找到版本号  
        let tag = await this.fetchTag(repo);

        // 3. 下载
        let downloadUrl = await this.download(repo,tag);

        // 4. 编译模板

    }
}

module.exports = Creator;